<template>
    <div class="form">
        <wp-form-group
            ref="customerformgroup"
            :formTitle="$st('wp-ji-ben-xin-xi')"
            v-model="customerForm"
            :groupRules="customerRules"
            :formProp="customerProp">
            <template #regiontext>
                <van-field
                    v-model="customerForm.regiontext"
                    :rules="customerRules.regiontext"
                    is-link
                    readonly
                    input-align="right"
                    :placeholder="$st('wp-qing-xuan-ze')"
                    @click="areaPicker = true"
                >
                    <template #label>
                        <span class="red">*</span>
                        <span>{{ $st('wp-suo-zai-di-qu') }}</span>
                    </template>
                </van-field>
            </template>
            <template #location>
                <van-field
                    v-model="customerForm.location"
                    is-link
                    readonly
                    input-align="right"
                    :placeholder="$st('wp-qing-xuan-ze')"
                    @click="mapPicker = true"
                >
                    <template #label>
                        <span>{{ $st('wp-ding-wei') }}</span>
                    </template>
                </van-field>
            </template>
        </wp-form-group>
        <wp-form-group
            ref="customizeformgroup"
            :formTitle="$st('wp-zi-ding-yi-xin-xi')"
            v-model="customizeForm"
            :groupRules="customizeRules"
            :formProp="customizeProp">
        </wp-form-group>
    </div>
    <area-popup
        :areaShow="areaPicker"
        :region="customerForm.region"
        @onAreaConfirm="onAreaConfirm"
        @onAreaCancel="onAreaCancel">
    </area-popup>
    <baidu-map-popup
        :popupShow="mapPicker"
        @confirm="mapConfirm"
        :point="customerForm.point"
        @cancel="mapCancel">
    </baidu-map-popup>
    <div class="button-div-fixed">
        <van-button
            class="btn"
            @click="concel">
            {{ $st('wp-qu-xiao') }}
        </van-button>
        <van-button
            class="btn"
            @click="resetForm">
            {{ $st('wp-zhong-zhi') }}
        </van-button>
        <van-button
            class="btn"
            type="primary"
            @click="submitForm">
            {{ $st('wp-bao-cun') }}
        </van-button>
    </div>
</template>
<script>
import { useRouter, useRoute } from 'vue-router';
import { selfI18n } from '@/i18n/index';
import { reactive, toRefs, onMounted, ref } from 'vue';
import useCustomerManageSetup from '@/setup/workbench/CustomerManageSetup.js';
import AreaPopup from '@/components/_common/areaPopup.vue';
import BaiduMapPopup from '@/components/_common/BaiduMapPopup.vue';
import useMaintenanceMembersSetup from '@/setup/maintenanceteam/MaintenanceTeamMembersSetup';
import { showSuccess } from '@/util/MessageDeal';
import RegConfig from '@/util/RegConfig.js';

export default {
    components: {
        AreaPopup,
        BaiduMapPopup
    },
    setup (props, ctx) {
        const $st = selfI18n;
        const route = useRoute();
        const router = useRouter();
        const customerformgroup = ref(null);
        const customizeformgroup = ref(null);
        const { getCustomrosterCustomparams, postCustomrecord, getCustomrecordOne, putCustomrecord } = useCustomerManageSetup();
        const { getAllMaintenanceTeamMembers } = useMaintenanceMembersSetup();
        const checkPhone = (value) => {
            if (value && !RegConfig.phone_number.test(value)) {
                return false;
            }
            return true;
        };

        const checkAccount = (value) => {
            if (value && !RegConfig.username.test(value)) {
                return false;
            }
            return true;
        };

        const state = reactive({
            areaPicker: false,
            mapPicker: false,
            customerForm: {},
            customizeForm: {},
            customerRules: {
                customer_name: [
                    { required: true, message: $st('wp-qing-tian-xie') }
                ],
                regiontext: [
                    { required: true, message: $st('wp-qing-xuan-ze') }
                ],
                seller_account: [
                    { required: true, message: $st('wp-qing-xuan-ze') }
                ],
                contactway: [
                    { validator: checkPhone, message: $st('wp-qing-shu-ru-zheng-que-de-shou-ji-hao') }
                ],
                contactaccount: [
                    { validator: checkAccount, message: $st('username_ruler_alert') }
                ]
            },
            customizeRules: {},
            customerProp: [{
                id: 'customer_id',
                label: $st('wp-ke-hu-id'),
                disabled: true,
                placeholder: $st('wp-xi-tong-zi-dong-sheng-cheng')
            }, {
                id: 'customer_name',
                label: $st('wp-ke-hu-ming-cheng'),
                isrequired: true,
                placeholder: $st('wp-qing-tian-xie'),
                maxlength: '20'
            }, {
                id: 'regiontext',
                label: $st('wp-suo-zai-di-qu'),
                isrequired: true,
                placeholder: $st('wp-qing-xuan-ze')
            }, {
                id: 'mainbusiness',
                label: $st('wp-zhu-ying-ye-wu'),
                placeholder: $st('wp-qing-tian-xie'),
                maxlength: '200'
            }, {
                id: 'contactperson',
                label: $st('wp-ke-hu-lian-xi-ren'),
                placeholder: $st('wp-qing-tian-xie'),
                maxlength: '20'
            }, {
                id: 'contactway',
                label: $st('wp-shou-ji-hao'),
                placeholder: $st('wp-qing-tian-xie'),
                maxlength: '11'
            }, {
                id: 'address',
                label: $st('wp-lian-xi-di-zhi'),
                placeholder: $st('wp-qing-tian-xie'),
                maxlength: '50'
            }, {
                id: 'location',
                label: $st('wp-ding-wei'),
                placeholder: $st('wp-qing-xuan-ze')
            }, {
                id: 'contactaccount',
                label: $st('wp-yun-zhang-hao'),
                placeholder: $st('wp-qing-tian-xie'),
                maxlength: '20'
            }, {
                id: 'seller_account',
                label: $st('wp-wei-bao-fu-ze-ren'),
                isrequired: true,
                formtype: 'selectfield',
                columns: [],
                placeholder: $st('wp-qing-xuan-ze')
            }, {
                id: 'remark',
                label: $st('wp-bei-zhu'),
                formtype: 'textarea',
                maxlength: 200,
                placeholder: $st('wp-qing-tian-xie-bei-zhu-200-zi-yi-nei')
            }],
            customizeProp: [],
            regionObj: {
                country: '',
                province: '',
                city: ''
            },
            typeObj: {
                new: $st('wp-xin-jian-ke-hu'),
                edit: $st('wp-bian-ji-ke-hu')
            },
            customerInfo: {}
        });

        // 获取自定义参数
        const getCustomParams = () => {
            getCustomrosterCustomparams().then((data) => {
                data.value.forEach((item) => {
                    const obj = {
                        id: item.md5name,
                        label: item.originname,
                        placeholder: $st('wp-qing-tian-xie'),
                        maxlength: 50
                    };
                    state.customizeProp.push(obj);
                });
            });
        };

        // 获取维保负责人
        const getAllMembers = () => {
            getAllMaintenanceTeamMembers().then((data) => {
                state.customerProp[9].columns = data.value.map((item) => {
                    item.text = item.alias ? `${item.account}(${item.alias})` : item.account;
                    item.value = item.account;
                    return item;
                });
            });
        };

        // 选择地区确认
        const onAreaConfirm = (area) => {
            state.customerForm.region = area;
            state.customerForm.regiontext = area.country + area.province + area.city;
            state.areaPicker = false;
        };

        // 地区选择取消
        const onAreaCancel = () => {
            state.areaPicker = false;
        };

        // 定位选择确定
        const mapConfirm = (addressposition) => {
            state.customerForm.address = addressposition.address;
            state.customerForm.location = addressposition.point.lng.toFixed(12) + ',' + addressposition.point.lat.toFixed(12);
            state.customerForm.point = addressposition.point;
            mapCancel();
        };

        // 定位选择取消
        const mapCancel = () => {
            state.mapPicker = false;
        };

        // 重置
        const resetForm = () => {
            state.customerForm = {};
            state.customizeForm = {};
            state.regionObj.country = '';
            state.regionObj.province = '';
            state.regionObj.city = '';
            if (route.query.type === 'edit') {
                state.customerForm.customer_id = state.customerInfo.customer_id;
            }
        };

        // 提交
        const submitForm = async () => {
            console.log(state.customerForm);
            await customerformgroup.value.validate();
            await customizeformgroup.value.validate();
            const param = {
                ...state.customerForm,
                customparams: []
            };
            param.customparams = state.customizeProp.map((item) => {
                return {
                    md5name: item.id,
                    originname: item.label,
                    value: state.customizeForm[item.id] || ''
                };
            });
            if (route.query.type === 'new') {
                newCustomer(param);
            } else if (route.query.type === 'edit') {
                editCustomer(param);
            }
        };

        // 新增客户
        const newCustomer = (param) => {
            postCustomrecord(param).then((data) => {
                showSuccess($st('wp-tian-jia-cheng-gong'));
                concel();
            });
        };

        // 编辑客户
        const editCustomer = (param) => {
            putCustomrecord(param).then((data) => {
                showSuccess($st('wp-bian-ji-cheng-gong'));
                concel();
            });
        };

        // 取消
        const concel = () => {
            router.push('/customerManage');
        };

        // 获取客户详情
        const getCustomerDetail = () => {
            getCustomrecordOne({
                customer_id: route.query.customer_id
            }).then((data) => {
                state.customerInfo = state.customerForm = data.value;
                data.value.customparams.forEach((item) => {
                    state.customizeForm[item.md5name] = item.value;
                });
                const pointArr = data.value.location.split(',');
                state.customerForm.point = {
                    lng: pointArr[0],
                    lat: pointArr[1]
                };
                state.customerForm.regiontext = data.value.region ? data.value.region.country + data.value.region.province + data.value.region.city : '';
            });
        };

        onMounted(async () => {
            getCustomParams();
            await getAllMembers();
            if (route.query.type === 'edit' && route.query.customer_id) {
                getCustomerDetail();
            }
            document.title = state.typeObj[route.query.type];
        });

        return {
            ...toRefs(state),
            onAreaConfirm,
            resetForm,
            submitForm,
            concel,
            onAreaCancel,
            customerformgroup,
            customizeformgroup,
            mapCancel,
            mapConfirm
        };
    }
};
</script>
<style lang="scss" scoped>
.form {
    padding-bottom: 73px;
    background: #EDEDED;
}
.button-div-fixed {
    position:fixed;
    padding: 7px 15px;
    bottom: 0;
    background-color: #fff;
    height: 53px;
    box-sizing: border-box;
    width: 100%;
    display: flex;
    .btn {
        height: 40px;
        flex: 1;
        margin-right: 10px;
        border-radius: 4px;
        &:last-child {
            margin-right: 0;
        }
    }
}
</style>
